import { defineStore } from 'pinia'
import config from '@/config'
import { initiaStore } from '@/stores/initialization.js'

export const browserStore = defineStore('browser', () => {
    const initiaStores = initiaStore()
    const state = reactive({
        status: 0,  // 0-获取参数中  1-浏览器启动中
        map: {},
        data: {}
    })

    const openBrowser = (row) => {
        state.data[row.fingerprint_id] = {}
        state.data[row.fingerprint_id].formData = JSON.parse(JSON.stringify(row.environment_data))
        state.map = initiaStores.initiaData.map
        state.data[row.fingerprint_id].status = 0

        state.data[row.fingerprint_id].browserParams = {
            fingerprint_id: row.fingerprint_id,
            id: row.id,
            number: row.number,
            name: row.environment_data.base.name,
            path: getPath(row.fingerprint_id),
            deviceType: row.environment_data.base.operate,
            setting: {
                userAgent: row.environment_data.base.userAgent.user_agent.trim(),
                userAgentMetadata: {
                    brands: [
                        { brand: 'Not.A/Brand', version: '24' },
                        { brand: 'Chromium', version: `${row.environment_data.base.browser.version}` },
                        { brand: 'Google Chrome', version: `${row.environment_data.base.browser.version}` }
                    ],
                    platform: row.environment_data.base.operate,
                    platformVersion: '10.15.7',
                    mobile: row.environment_data.base.operate == 'Windows' || row.environment_data.base.operate == 'macOS' ? false : true,
                    architecture: row.environment_data.base.operate == 'Windows' || row.environment_data.base.operate == 'macOS' ? 'x86' : 'arm',
                    model: getdevice(row.fingerprint_id, row),
                },
            },
            proxy: {
                type: -1
            },
            hign: {
                language: row.environment_data.hign.language.type == 0 ? '' : row.environment_data.hign.language.languages[0],
                timeZone: row.environment_data.hign.timeZone.type == 0 ? '' : getLabel(row.environment_data.hign.timeZone.timeZone, state.map.timeZones),
                location: row.environment_data.hign.location,
                resolution: getresolution(row.fingerprint_id, row),
                font: row.environment_data.hign.font,
                fontprint: row.environment_data.hign.fontprint == 0 ? 'NOISE' : 'REAL',
                webrtc: {
                    type: row.environment_data.hign.webrtc,
                    emsIP: row.environment_data.hign.emsIP
                },
                speechVoice: row.environment_data.hign.speechVoices,
                media: row.environment_data.hign.media,
                concurrency: row.environment_data.hign.concurrency,
                memory: row.environment_data.hign.memory,
                donottrack: row.environment_data.hign.donottrack,
                battery: row.environment_data.hign.battery,
                portProtect: getportProtect(row.fingerprint_id, row),
                startParams: row.environment_data.hign.startParams != '' ? row.environment_data.hign.startParams.split(/\r?\n/) : [],
                webNotice: row.environment_data.hign.webNotice,
                loadingImg: row.environment_data.hign.loadingImg,
                imgSize: row.environment_data.hign.imgSize,
                loadingVide: row.environment_data.hign.loadingVide,
                loadingMusic: row.environment_data.hign.loadingMusic,
            },
            user: row.environment_data.user

        }

        onSubmit(row.fingerprint_id)
    }

    const getPath = (fingerprint_id) => {
        let selectMap = []
        if (state.data[fingerprint_id].formData.base.browser.type == 'ChroBrowser') {
            selectMap = state.map.Chrome
        } else {
            selectMap = state.map.Firefox
        }
        let path = ''
        selectMap.forEach(item => {
            if (item.value == state.data[fingerprint_id].formData.base.browser.version) {
                path = item.path
            }
        });

        return path
    }

    const getdevice = (fingerprint_id, row) => {
        let model = ''
        if (row.environment_data.base.operate == 'Windows') {
            model = 'Windows PC'
        } else if (row.environment_data.base.operate == 'macOS') {
            model = 'Macintosh'
        } else {
            model = state.data[fingerprint_id].formData.base.model
        }

        return model
    }

    // 分辨率
    const getresolution = (fingerprint_id, row) => {
        let a = {
            name: '',
            resolutionW: '',
            resolutionH: ''
        }
        if (row.environment_data.hign.resolution.type == 0) {
            a.name = ''
        } else if (row.environment_data.hign.resolution.type == 1) {
            a.name = ''
        } else if (row.environment_data.hign.resolution.type == 2) {
            a = {
                name: `${row.environment_data.hign.resolution.resolutionW}x${row.environment_data.hign.resolution.resolutionH}`,
                resolutionW: row.environment_data.hign.resolution.resolutionW,
                resolutionH: row.environment_data.hign.resolution.resolutionH
            }
        } else {
            a = {
                name: row.environment_data.hign.resolution.type,
                resolutionW: '',
                resolutionH: ''
            }

            const regex = /(\d+)x(\d+)/;
            const match = row.environment_data.hign.resolution.type.match(regex);

            if (match) {
                a.resolutionW = match[1]; // x前的数字
                a.resolutionH = match[2];  // x后的数字
            }
        }

        return a
    }

    const getportProtect = (fingerprint_id, row) => {
        let a = {
            type: row.environment_data.hign.portProtect.type,
            ports: []
        }

        if (row.environment_data.hign.portProtect.type == 1) {
            let sortedArray = row.environment_data.hign.portProtect.ports.split(',')
                .map(Number)
                .sort((a, b) => a - b);

            sortedArray.forEach((item, index) => {
                let s = 1
                let e = 1
                if (index == 0) {
                    s = 1
                    e = item - 1
                } else {
                    s = sortedArray[index - 1] + 1
                    e = item - 1
                }
                a.ports.push(`${s}-${e}`)

                if (index == sortedArray.length - 1 && item < 65535) {
                    let s2 = item + 1
                    let e2 = 65535
                    a.ports.push(`${s2}-${e2}`)
                }
            });

        }

        return a
    }







    const onSubmit = async (fingerprint_id) => {
        console.log(state.data[fingerprint_id].browserParams);

        state.data[fingerprint_id].status = 1
        try {
            if (!config.isWeb) {
                state.data[fingerprint_id].status = 1
                await window.electron.openWebview(JSON.stringify(state.data[fingerprint_id].browserParams))
            }
        } catch (error) {
            console.log(error)
        }
    }

    const getLabel = (value, options) => {
        let label = ''
        options.forEach(item => {
            if (item.value == value) {
                label = item.label
            }
        });

        return label
    }

    const getLabels = (value, options) => {
        let label = []
        options.forEach(item => {
            if (value.includes(item.value)) {
                label.push(item.label)
            }
        });

        return label.join(',')
    }

    onMounted(() => {
        window.electron.closeBrowser((event, msg) => {
            if (state.data[msg.fingerprint_id]) {
                delete state.data[msg.fingerprint_id]
            }
        })
    })


    return {
        state,
        openBrowser
    }
})